﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

using System.Collections.Generic;

using Microsoft.AspNetCore.Mvc;
using ZhonTai.DynamicApi.Attributes;
using ZhonTai.Industry.Core.Consts;
using ZhonTai.DynamicApi;
using ZhonTai.Industry.Domain.PLCBlock;
using ZhonTai.Admin.Services;
using ZhonTai.Industry.Services.PLCBlock.Dto;
using ZhonTai.Admin.Core.Dto;
using ZhonTai.Industry.Services.PLCBlock;
using ZhonTai.Industry.Services.WorkStation.Dto.Input;
using ZhonTai.Industry.Services.PLCBlock.Dto.Input;
using ZhonTai.Industry.Services.PLCBlock.Dto.Output;
using ZhonTai.Industry.Domain.WorkStation;

namespace SYH.Industry.Services.PLCBlock
{
    /// <summary>
    /// PLC数据块服务
    /// </summary>
    [DynamicApi(Area = IndustryConsts.AreaName)]
    public class PLCBlockService : BaseService, IPLCBlockService, IDynamicApi
    {
        private IPLCBlockRepository _pLCBlockRepository => LazyGetRequiredService<IPLCBlockRepository>();
        private IWorkStationRepository _workStationRepository => LazyGetRequiredService<IWorkStationRepository>();

        public PLCBlockService()
        {
        }

        /// <summary>
        /// 查询
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet]
        public async Task<PLCBlockGetOutput> GetAsync(long id)
        {
            var output = await _pLCBlockRepository.GetAsync<PLCBlockGetOutput>(id);
            return output;
        }

        /// <summary>
        /// 列表查询
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<IEnumerable<StationBlockGetListOutput>> GetListAsync(PLCBlockGetListInput input)
        {
            List<StationBlockGetListOutput>? selectStation = await _workStationRepository.Select
               .OrderBy(o => o.Sort)
               .ToListAsync<StationBlockGetListOutput>(t => new StationBlockGetListOutput { StationId = t.Id, LineName = t.ProductionLine.LineName });
            var result = selectStation.Select(s =>
            {
                var plcBlocks = _pLCBlockRepository.Select
                    .Where(w => w.WorkStationId == s.StationId)
                    .WhereIf(input.Address.HasValue && input.Address > 0, w => w.Address == input.Address)
                    .OrderBy(o => o.Sort)
                    .ToList<PLCBlockGetListOutput>();
                s.StationBlock = plcBlocks;
                return s;
            }).ToList();
            return result;
        }

        /// <summary>
        /// 分页查询
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<PageOutput<PLCBlockGetPageOutput>> GetPageAsync(PageInput<PLCBlockGetPageInput> input)
        {
            var filter = input.Filter;
            var select = _pLCBlockRepository.Select
                .WhereDynamicFilter(input.DynamicFilter)
                .Count(out var total);
            if (input.SortList != null && input.SortList.Count > 0)
            {
                input.SortList.ForEach(sort =>
                {
                    select = select.OrderByPropertyNameIf(sort.Order.HasValue, sort.PropName, sort.IsAscending.Value);
                });
            }
            else
            {
                select = select.OrderBy(a => a.Sort);
            }
            var list = await select.OrderByDescending(c => c.Id)
             .Page(input.CurrentPage, input.PageSize)
             .ToListAsync(t => new PLCBlockGetPageOutput() { StationCode = t.WorkStation.StationCode, LineName = t.WorkStation.ProductionLine.LineName });

            //关联查询代码

            var data = new PageOutput<PLCBlockGetPageOutput> { List = list, Total = total };

            return data;
        }

        /// <summary>
        /// 新增
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<long> AddAsync(PLCBlockAddInput input)
        {
            var entity = Mapper.Map<PLCBlockEntity>(input);
            entity.Enabled = true;
            var id = (await _pLCBlockRepository.InsertAsync(entity)).Id;

            return id;
        }

        /// <summary>
        /// 更新
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPut]
        public async Task UpdateAsync(PLCBlockUpdateInput input)
        {
            var entity = await _pLCBlockRepository.GetAsync(input.Id);
            if (!(entity?.Id > 0))
            {
                throw ResultOutput.Exception("PLC数据块不存在！");
            }

            Mapper.Map(input, entity);
            await _pLCBlockRepository.UpdateAsync(entity);
        }

        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpDelete]
        public async Task<bool> DeleteAsync(long id)
        {
            return await _pLCBlockRepository.DeleteAsync(id) > 0;
        }

        /// <summary>
        /// 软删除
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpDelete]
        public async Task<bool> SoftDeleteAsync(long id)
        {
            return await _pLCBlockRepository.SoftDeleteAsync(id);
        }

        /// <summary>
        /// 批量软删除
        /// </summary>
        /// <param name="ids"></param>
        /// <returns></returns>
        [HttpPut]
        public async Task<bool> BatchSoftDeleteAsync(long[] ids)
        {
            return await _pLCBlockRepository.SoftDeleteAsync(ids);
        }

        /// <summary>
        /// 设置启用
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task SetEnableAsync(PLCBlockSetEnableInput input)
        {
            var entity = await _pLCBlockRepository.GetAsync(input.PLCBlockId);
            entity.Enabled = input.Enabled;
            await _pLCBlockRepository.UpdateAsync(entity);
        }
    }
}